package com.plian.system.config;

import com.plian.Tools.StringUtil;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;

//@WebFilter(urlPatterns = "/*",filterName = "channelFilter")
public class ChannelFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        ServletRequest requestWrapper = null;

        String contentType = servletRequest.getContentType();
        if (StringUtil.isNotBlank(contentType) && contentType.contains("multipart/form-data")){
            //文件类型特殊处理
            CommonsMultipartResolver commonsMultipartResolver =
                    new CommonsMultipartResolver(servletRequest.getServletContext());
            MultipartHttpServletRequest multiReq = commonsMultipartResolver.resolveMultipart((HttpServletRequest)servletRequest);
            filterChain.doFilter(multiReq, servletResponse);
        }else {
            if(servletRequest instanceof HttpServletRequest) {
                requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
            }
            if(requestWrapper == null) {
                filterChain.doFilter(servletRequest, servletResponse);
            } else {
                filterChain.doFilter(requestWrapper, servletResponse);
            }
        }


    }

    @Override
    public void destroy() {

    }
}
